package com.example.sentinel.application;

import com.example.sentinel.application.Impl.CoreBizService;
import com.example.sentinel.domain.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.ThreadLocalRandom;

@Service
@Slf4j
public class CoreBizServiceImpl implements CoreBizService {
    public Result process() {
        //此处不处理异常，而是直接抛出
        delay();
        if(shouldFail()){
            throw new RuntimeException("服务异常");
        }else{
            return Result.success("处理成功");
        }
    }

    //模拟随机延迟
    private void delay(){
        //使用threadLocalRandom获取随机数，为每一个线程维护一个随机数器，适合高并发的场景
        int delay = ThreadLocalRandom.current().nextInt(100, 301);
        try {
            Thread.sleep(delay);
        } catch (Exception e) {
            Thread.currentThread().interrupt();
        }
    }

    //成功或是失败
    private boolean shouldFail(){
        return ThreadLocalRandom.current().nextBoolean();
    }
}
